#-*-coding:utf-8 -*-


from sklearn.feature_extraction import DictVectorizer  #feature特征 extraction提取 dict字典 vectorizer向量化程序  
import csv   #csv程序  
from sklearn import preprocessing   #preprocessing预处理  
from sklearn import tree   #tree树  
from sklearn.externals.six import StringIO  #external外部的   string字符串  
from __builtin__ import str

allElectronicsData = open(r'dataSet.csv','rb')  #electronics电子工业  
reader = csv.reader(allElectronicsData)  
headers = reader.next()  

print( "headers:\n\t"+str(headers) )  
  
featureList = []  #特征示例  
labelList = []   #标号表  
  
for row in reader:#行  
    labelList.append(row[len(row) - 1])  
    rowDict = {}  
    for i in range(1, len(row) - 1):  
        rowDict[headers[i]] = row[i]  
    featureList.append(rowDict)  
      
print( "featureList:\n\t"+str(featureList) )


vec = DictVectorizer()  
dummyX = vec.fit_transform(featureList).toarray()  
  
print("dummyX:\n\t" + str(dummyX))  #dummy虚拟的  
print( "feature_names:\n\t"+str(vec.get_feature_names()) )  
  
print("labelList:\n\t" + str(labelList))  
  

lb = preprocessing.LabelBinarizer()  
dummyY = lb.fit_transform(labelList)  
print("dummyY:" + str(dummyY))  
  

clf = tree.DecisionTreeClassifier(criterion='entropy')  #熵  
clf = clf.fit(dummyX,dummyY)  
print("clf:" + str(clf))  
  

with open("allElectronicInformationGainOri.dot",'w') as f:  
    f = tree.export_graphviz(clf,feature_names=vec.get_feature_names(),out_file = f)  
      

#进行预测
oneRowX = dummyX[0,:]  
print("oneRowX:\n\t" + str(oneRowX))  
print( "feature_names:\n\t"+str(vec.get_feature_names()) )  
  
newRowX = oneRowX  
  
#newRowX[0] = 1  
#newRowX[2] = 0 
print("newRowX:\n\t" + str(newRowX))  

predictedY = clf.predict([newRowX] )  
print("predictedY:\n\t" + str(predictedY)) 







